import { getZodErrorMessage } from "@packages/shared"
import { toRefs, type Ref } from "vue"
import { z } from "zod"

export type FormValidType = {
    value: string | number | undefined,
    message: string
}

export type ModelValid = Ref<Record<string, FormValidType>>

const useModelValid = (model: ModelValid, schema: z.ZodObject<any>) => {

    const doValidField = (field: string) => {
        const fieldSchema = schema.shape[field]
        const modelField = model.value[field]

        const result = fieldSchema.safeParse(modelField?.value)

        if (!result.success) {
            if (modelField)
                modelField.message = getZodErrorMessage(result.error).split(':')[1] || ''
        }
        else
            if (modelField)
                modelField.message = ''
        return result.success
    }

    const doValidAll = () => {
        let ok = true
        const result: Record<string, string | number | undefined> = {}
        for (const field in model.value) {
            if (doValidField(field) === false)
                ok = false
            result[field] = model.value[field]?.value ?? ''
        }
        return { ok, result }
    }

    return {
        doValidField,
        doValidAll
    }

}

export default useModelValid